//
//  LXNetworkOperation.m
//  ProjectSource_Demo
//
//  Created by Liu on 16/2/18.
//  Copyright © 2016年 AngryBear. All rights reserved.
//

#import "LXNetworkOperation.h"

@interface LXNetworkOperation ()<NSURLSessionDataDelegate>
{
    NSMutableData *_data;
}
@property (nonatomic, strong) NSURLSession *session;

@end

@implementation LXNetworkOperation

+ (instancetype)HTTPRequestOperationWithRequest:(NSURLRequest *)request
                                         params:(NSDictionary *)params
                              completionHandler:(void (^)())completion
                                 failureHandler:(void (^)())failure
{
    LXNetworkOperation *operation = [[LXNetworkOperation alloc] init];
    NSMutableURLRequest *mRequest = [[NSMutableURLRequest alloc] initWithURL:request.URL cachePolicy:request.cachePolicy timeoutInterval:request.timeoutInterval];
    mRequest.HTTPMethod = request.HTTPMethod;
    if (params) {
        mRequest.HTTPBody = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
    }
    
    operation.request = mRequest;
    operation.completion = completion;
    operation.failure = failure;
    
    return operation;
}

- (void)main
{
    if (self.isCancelled) {
        return;
    }
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    config.timeoutIntervalForRequest = 5;
    self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionTask *task = [self.session dataTaskWithRequest:self.request];
    [task resume];
}

#pragma mark - NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
{
    NSLog(@"%s %@", __func__, response);
    _data = [NSMutableData data];
    [_data setLength:0];
    
    completionHandler(NSURLSessionResponseAllow);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask willCacheResponse:(NSCachedURLResponse *)proposedResponse completionHandler:(void (^)(NSCachedURLResponse * _Nullable))completionHandler
{
    NSLog(@"%s %@", __func__, proposedResponse);
    completionHandler(proposedResponse);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data
{
    [_data appendData:data];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (!error) {
        NSString *string = [[NSString alloc] initWithData:_data encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:_data options:0 error:nil];
        self.completion(self, dic);
    }
    else {
        self.failure(self, error);
    }
}

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error
{
    NSLog(@"%s %@", __func__, error);
    self.failure(self, error);
}

@end
